package com.jfinalnat.httpclient.sdk;

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HttpContext;
import org.apache.log4j.Logger;

import com.chunyv.maas.pojo.token.TokenTimerHandler;
import com.jfinalnat.token.factory.TokenTimerHandlerFactory;

public class HttpCrossIntercepter implements HttpRequestInterceptor {
	
	private static final Logger LOG = Logger.getLogger(Class.class);

	public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
		
        System.out.println("________________________request前______________________________");
        Header[] heads1 = request.getAllHeaders();
        for (int i = 0; i < heads1.length; i++) {
        	if (heads1[i].getName().equalsIgnoreCase("Cookie"))
			System.out.println(heads1[i].getName()+", "+heads1[i].getValue());
		}
		
        new CookieService().CookieFirstHandler(request);
        //new CookieService().CookieHandler(request);
		
		//加入iPlanetDirectoryPro
        if (PoolingHttpClientConfig.isEnable) {
        	
        	Header cookie = request.getFirstHeader("Cookie");
        	TokenTimerHandler  tokenTimerHandler = TokenTimerHandlerFactory.createSSLSocketFactoryImpl(PoolingHttpClientConfig.amHost, PoolingHttpClientConfig.updateTime, PoolingHttpClientConfig.updateFastTime, PoolingHttpClientConfig.keyStorePath, PoolingHttpClientConfig.password);
        	if (null != cookie) {
        		String value = cookie.getValue();
        		value = "iPlanetDirectoryPro=" + tokenTimerHandler.getTokenURLEncode() + "; " + value;
        		request.setHeader("Cookie", value);
        		
        	} else {
        		request.addHeader(new BasicHeader("Cookie", "iPlanetDirectoryPro="+tokenTimerHandler.getTokenURLEncode()));
        	}
        }
        
        
        System.out.println("________________________request______________________________");
        Header[] heads = request.getAllHeaders();
        for (int i = 0; i < heads.length; i++) {
        	if (heads[i].getName().equalsIgnoreCase("Cookie"))
        	System.out.println(heads[i].getName()+", "+heads[i].getValue());
		}
	}

}
